<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 警告区 -->
      <el-alert title="消息提示的文案" type="info" center show-icon :closable="false"></el-alert>
      <!--步骤进度条-->
      <el-steps :active="activeName - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="动态参数"></el-step>
        <el-step title="静态参数"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>

      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <!--左侧边栏目-->
        <el-tabs
          v-model="activeName"
          tab-position="left"
          :before-leave="tabBeforeLeave"
          @tab-click="handleClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item prop="goods_name" label="商品名称">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price" label="商品价格">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品重量">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight" label="商品数量">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_cat" label="商品分类">
              <el-cascader
                expand-trigger="hover"
                :options="catThreeList"
                v-model="addForm.goods_cat"
                :props="catThreeProps"
                @change="catThreeChange()"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyParams" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item2"
                  :key="item2"
                  v-for="item2 in item.attr_vals2"
                  border
                  @change="clickCheckbox(item.attr_vals2,item2)"
                  ref="checkboxRef"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- label中如果使用变量需要绑定label这个属性即:label="xx" 如果是固定字符串写成label="xx"即可 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyParams"
              :key="item.attr_id"
              label-width="150px"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-dialog title="提示" :visible.sync="previewVisible" width="50%">
              <img :src="previewImg" alt class="img-preview" height="400" />
            </el-dialog>
            <el-upload
              :action="uploadUrl"
              :on-preview="uploadPreview"
              :on-remove="uploadRemove"
              :on-success="uploadSuccess"
              list-type="picture"
              :headers="uploadParam"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quillEditor v-model="addForm.goods_introduce" ref="myQuillEditor"></quillEditor>
            <el-row>
              <el-col :push="8">
                <el-button type="primary" @click="addGoods()">添加商品</el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入富文本编辑器相关
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 导入lodash
import _ from 'lodash'
export default {
  components: {
    // 富文本编辑器组件
    quillEditor
  },
  created () {
    this.getCatThreeList()
  },
  data () {
    return {
      activeName: '0',
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '', // 商品介绍
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '商品名称必填', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格必填', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品重量必填', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品数量必填', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选取商品分类', trigger: 'blur' }
        ]
      },
      catThreeList: [],
      catThreeId: 0,
      catThreeProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态参数
      manyParams: [],
      // 静态参数
      onlyParams: [],
      // 上传图片参数

      // 上传图片服务器地址
      uploadUrl: 'http://127.0.0.1:11333/api/private/v1/' + 'upload',
      // 上传图片需要的参数
      uploadParam: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片路径名
      previewImg: '',
      // 预览图片dialog开关
      previewVisible: false
    }
  },
  methods: {
    // 获得级联选择器需要的3级别分类信息
    async getCatThreeList () {
      const { data: dt } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      console.log(dt)

      this.catThreeList = dt.data
    },
    catThreeChange () {
      var len = this.addForm.goods_cat.length
      if (len === 3) {
        this.catThreeId = this.addForm.goods_cat[2]
      } else {
        this.addForm.goods_cat = []
        this.catThreeId = 0
      }
    },
    // 标签切换之前处理
    tabBeforeLeave (activeName, oldActiveName) {
      console.log(activeName, oldActiveName)
      // 当前如果选中"动态参数"或"静态参数"标签，则要求已经选定了第3级别分类
      if (+activeName >= 1) {
        if (this.catThreeId === 0) {
          this.$message.error('请在基本信息中选取第三级商品分类')
          return false
        }
      }
    },
    // 侧边栏 点击事件
    async handleClick () {
      // 判断点击了“动态参数”标签就根据分类获取对应的参数信息
      if (this.activeName === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.catThreeId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        // 把attr_vals由空格分割的字符串 变为数组
        // 通过attr_vals和attr_vals2对参数值进行接收
        // attr_vals: 对表单负责，选取或接收实际的参数值
        // attr_vals2: 对展示负责，在添加商品的动态参数中显示全部的参数项目
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.attr_vals2 = item.attr_vals
        })
        this.manyParams = res.data
        console.log(this.manyParams)
      } else if (this.activeName === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.catThreeId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        this.onlyParams = res.data
        console.log(this.onlyParams)
      }
    },
    clickCheckbox (ss, s) {
      var i = ss.indexOf(s)
      ss.splice(i, 1)
    },
    // 上传图片成功-把图片路径名存储给addForm.pics成员
    uploadSuccess (result) {
      if (result.meta.status !== 200) {
        return this.$message.error('图片上传失败')
      }

      // console.log(result)
      // 把图片路径名通过对象形式存储给addForm.pics成员
      var o = { pic: result.data.tmp_path }
      this.addForm.pics.push(o)
    },
    // 预览上传图片
    uploadPreview (result) {
      console.log(result)
      // 被预览图片路径名
      this.previewImg = result.url
      console.log(result.url)
      // dialog弹层开关
      this.previewVisible = true
    },
    // 删除上传图片
    uploadRemove (result) {
      if (result.response.meta.status !== 200) {
        return this.$message.error('图片删除失败')
      }

      // 从pics中获取被删除图片所在的下标
      var i = this.addForm.pics.findIndex(item => {
        return item.pic === result.response.data.tmp_path
      })
      // 把图片路径名从pics中删除
      this.addForm.pics.splice(i, 1)
    },

    // 添加商品处理
    addGoods () {
      // 表单验证
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 把addForm复制一份，并对复制品进行操作
          var form = _.cloneDeep(this.addForm)
          // 数组变为字符串
          form.goods_cat = form.goods_cat.join(',')
          // 处理动态参数信息
          this.manyParams.forEach(item => {
            if (item.attr_vals.length > 0) {
              var newObj = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals.join(' ')
              }
              form.attrs.push(newObj)
            }
          })
          // 处理静态参数信息
          this.onlyParams.forEach(item => {
            if (item.attr_vals.trim()) {
              var newObj = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals
              }
              form.attrs.push(newObj)
            }
          })
          console.log(form)
          const { data: res } = await this.$http.post('goods', form)
          // 提示
          this.$message.success(res.meta.msg)
          // 页面跳转
          this.$router.push('goods')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps,
.el-tabs {
  margin-top: 20px;
}
// 预览图片img标签样式
.img-preview {
  width: 100%;
}
// 富文本编辑器设置样式
.quill-editor {
  margin-bottom: 15px;
  height: 200px;
  overflow: hidden;
}
</style>
